package com.yww.datastructure.heap;

import java.util.Arrays;
import java.util.Iterator;

/**
 * @author yww
 * @description 堆
 * @since 2024/2/7 20:03
 */
public class Heap implements IHeap {
    private int[] array;
    private int size;
    /**
     * true 大顶堆 - false 小顶堆
     */
    private boolean isMax;

    public Heap() {
        this(true, 10);
    }

    public Heap(boolean isMax) {
        this(isMax, 10);
    }

    public Heap(int[] array, boolean isMax) {
        this.array = array;
        this.isMax = isMax;
        this.size = array.length;
        heapify(); // 数组堆化
    }

    public Heap(boolean isMax, int capacity) {
        this.isMax = isMax;
        this.array = new int[capacity];
    }

    @Override
    public int peek() {
        if (isEmpty()) {
            throw new NullPointerException("堆空！");
        }
        return array[0];
    }

    @Override
    public int poll() {
        if (isEmpty()) {
            throw new NullPointerException("堆空！");
        }
        int val = array[0];
        swap(0, --size);
        down(0);
        return val;
    }

    @Override
    public int poll(int index) {
        if (isEmpty()) {
            throw new NullPointerException("堆空！");
        }
        int val = array[index];
        swap(index, --size);
        down(index);
        return val;
    }

    @Override
    public void replace(int replaced) {
        if (isEmpty()) {
            throw new NullPointerException("堆空！");
        }
        array[0] = replaced;
        down(0);
    }

    @Override
    public boolean offer(int offered) {
        if (size == array.length) {
            grow(); // 堆满，扩容
        }
        up(offered);
        size++;
        return true;
    }


    @Override
    public int[] sort() {
        int[] tempArr = Arrays.copyOf(this.array, array.length);
        int tempSize = size;
        while (size > 1) {
            swap(0, --size);
            down(0);
        }
        int[] sorted = Arrays.copyOf(this.array, tempSize);
        this.array = tempArr;
        this.size = tempSize;
        return sorted;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == array.length;
    }

    public int size() {
        return size;
    }

    public void transform() {
        this.isMax = !this.isMax;
        if (isEmpty()) {
            return;
        }
        heapify();
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            int p = 0;

            @Override
            public boolean hasNext() {
                return p < size;
            }

            @Override
            public Integer next() {
                return array[p++];
            }
        };
    }

    // 堆扩容
    private void grow() {
        int newCapacity = size + (size >> 1);
        int[] newArr = new int[newCapacity];
        System.arraycopy(array, 0, newArr, 0, size);
        array = newArr;
    }

    // 构建堆
    private void heapify() {
        for (int i = size / 2 - 1; i >= 0; i--) {
            down(i); // 从最后一个子树（非叶子节点）下潜
        }
    }

    // 上浮：offered上浮
    private void up(int offered) {
        int child = size;
        while (child > 0) {
            int parent = (child - 1) / 2;
            boolean gt = isMax ? offered > array[parent] : offered < array[parent];
            if (gt) {
                array[child] = array[parent];
            } else {
                break;
            }
            child = parent;
        }
        array[child] = offered;
    }

    // 下潜：parent下潜
    private void down(int parent) {
        if (parent >= size) {
            return;
        }
        int max = parent;
        int left = parent * 2 + 1;
        int right = left + 1;
        if (left < size && (isMax ? array[max] < array[left] : array[max] > array[left])) {
            max = left;
        }
        if (right < size && (isMax ? array[max] < array[right] : array[max] > array[right])) {
            max = right;
        }

        if (parent != max) {
            swap(max, parent);
            down(max);
        }
    }

    private void swap(int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}
